package org.lc.eic.messagingsystem.activemq;

import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStream;

import javax.jms.BytesMessage;
import javax.jms.JMSException;
import javax.jms.MessageProducer;
import javax.jms.Session;

import org.lc.eic.messagingsystem.OutgoingMessage;
import org.lc.eic.messagingsystem.exception.CreateOutgoingMessageException;
import org.lc.eic.messagingsystem.exception.SendMessageException;

public class MessagingReference implements
		org.lc.eic.messagingsystem.MessagingReference {

	private Session session;
	private MessageProducer messageProducer;

	public MessagingReference(Session session, MessageProducer messageProducer) {
		this.session = session;
		this.messageProducer = messageProducer;
	}

	public OutgoingMessage createMessageToSend()
			throws CreateOutgoingMessageException {

		return new org.lc.eic.messagingsystem.activemq.OutgoingMessage();

	}

	public void sendMessage(OutgoingMessage message)
			throws SendMessageException {

		org.lc.eic.messagingsystem.activemq.OutgoingMessage om = (org.lc.eic.messagingsystem.activemq.OutgoingMessage) message;

		BytesMessage bytesMessage;
		try {
			bytesMessage = session.createBytesMessage();
		} catch (JMSException e) {
			throw new SendMessageException("Failed create "
					+ BytesMessage.class.getName() + " impl. ", e);
		}

		InputStream instream = new ByteArrayInputStream(om
				.getByteArrayOutputStream().toByteArray());

		byte[] buffer = new byte[1024];
		int read;

		while (true) {
			try {
				read = instream.read(buffer);
			} catch (IOException e) {
				throw new SendMessageException(
						"Failed reading in-memory buffer..", e);
			}

			if (read == -1) {
				break;
			}

			try {
				bytesMessage.writeBytes(buffer, 0, read);
			} catch (JMSException e) {
				throw new SendMessageException(
						"Failed writing bytes to message.", e);
			}
		}

		try {
			this.messageProducer.send(bytesMessage);
		} catch (JMSException e) {
			throw new SendMessageException("Failed sending message. ", e);
		}

	}

}
